package com.rrd.hive.udf;

import com.rrd.hive.util.PIDValidator;
import com.weicai.caesar.CaesarUtil;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.hive.ql.udf.xml.UDFXPathUtil;
import org.apache.hadoop.io.Text;
import org.w3c.dom.Node;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


@Description(
        name = "pid_birth_day",
        value = "_FUNC_(pid, mode) - Get age from pid or caesar encode pid",
        extended = "Example:\n> SELECT _FUNC_('110102200101014832');\n  2001-01-01"
)
public class PidBirthDayUDF extends UDF {

    public Text evaluate(String pid) {
        if (pid == null || pid.equals("")) {
            return null;
        }
        Text res = new Text();
        if (CaesarUtil.isEncrypted(pid)) {
            pid = CaesarUtil.decode(pid);
        }
        if (pid.length() != 18 || !PIDValidator.isValidIDCard(pid)) {
            return null;
        }

        String birthday = pid.substring(6, 10) + "-" + pid.substring(10, 12) + "-" + pid.substring(12, 14);
        res.set(birthday);
        return res;
    }

    public Date parse(String strDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            return sdf.parse(strDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
//        PidBirthDayUDF dfu = new PidBirthDayUDF();
//        System.out.println(dfu.evaluate(CaesarUtil.encode("110102200101014832")));
        UDFXPathUtil xpath = new UDFXPathUtil();
        Node node = xpath.evalNode("<a><b>1</b></a>", "a");
        System.out.println(node.getFirstChild().getFirstChild().getNodeValue());
    }
}
